<template>
  <div class="statistics-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据统计分析</h1>
      <p class="desc">试题库与考试数据分布统计</p>
    </div>

    <!-- 统计选项卡 -->
    <div class="tabs">
      <div 
        class="tab-item" 
        :class="{ active: activeTab === 'paper' }"
        @click="activeTab = 'paper'"
      >
        试题库统计
      </div>
      <div 
        class="tab-item" 
        :class="{ active: activeTab === 'plan' }"
        @click="activeTab = 'plan'"
      >
        考试统计
      </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <div class="loading-spinner">加载中...</div>
    </div>

    <!-- 试题库统计内容 -->
    <div v-if="activeTab === 'paper' && !loading">
      <div class="stat-card">
        <h2 class="card-title">各试题库题型分布</h2>
        
        <!-- 题型说明 -->
        <div class="type-legend">
          <div class="legend-item">
            <span class="type-marker type-1"></span>
            <span>单选题</span>
          </div>
          <div class="legend-item">
            <span class="type-marker type-2"></span>
            <span>多选题</span>
          </div>
          <div class="legend-item">
            <span class="type-marker type-3"></span>
            <span>判断题</span>
          </div>
        </div>
        
        <!-- 柱状图容器 -->
        <div class="bar-chart-container">
          <div 
            class="chart-item" 
            v-for="(item, index) in paperData" 
            :key="index"
          >
            <div class="chart-label">{{ item.name }}</div>
            <div class="chart-bars">
              <div 
                class="chart-bar type-1"
                :style="{ height: getBarHeight(item.data.find(d => d.type === 1)?.count || 0) }"
                :title="`单选题: ${item.data.find(d => d.type === 1)?.count || 0}题`"
              ></div>
              <div 
                class="chart-bar type-2"
                :style="{ height: getBarHeight(item.data.find(d => d.type === 2)?.count || 0) }"
                :title="`多选题: ${item.data.find(d => d.type === 2)?.count || 0}题`"
              ></div>
              <div 
                class="chart-bar type-3"
                :style="{ height: getBarHeight(item.data.find(d => d.type === 3)?.count || 0) }"
                :title="`判断题: ${item.data.find(d => d.type === 3)?.count || 0}题`"
              ></div>
            </div>
            <div class="total-count">
              总计: {{ getTotalCount(item.data) }}题
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 考试统计内容 -->
    <div v-if="activeTab === 'plan' && !loading">
      <div class="stat-card">
        <h2 class="card-title">各考试数量分布</h2>
        
        <!-- 饼图容器 -->
        <div class="pie-chart-container">
          <div class="pie-chart" :style="{ maxWidth: '400px', margin: '0 auto' }">
            <canvas id="planPieChart"></canvas>
          </div>
          
          <!-- 列表数据 -->
          <div class="plan-list">
            <div 
              class="plan-item" 
              v-for="(item, index) in planData" 
              :key="index"
              :style="{ '--color': getPlanColor(index) }"
            >
              <div class="plan-color-marker"></div>
              <div class="plan-name">{{ item.name }}</div>
              <div class="plan-count">
                {{ item.count }} 次
                <div class="count-percentage">
                  {{ getPercentage(item.count) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && (paperData.length === 0 && planData.length === 0)">
      <div class="empty-icon">📊</div>
      <p>暂无统计数据</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, onUpdated } from 'vue'
import { selectPaperStatic, selectPlanStatic } from "@/api/common"

// 响应式数据
const activeTab = ref('paper'); // 默认显示试题库统计
const paperData = ref([]); // 试题库统计数据
const planData = ref([]); // 考试统计数据
const loading = ref(true);
const maxCount = ref(0); // 最大题目数量，用于计算柱状图高度
const totalPlanCount = ref(0); // 考试总数量，用于计算百分比
const toast = inject("toast");

// 初始化图表的函数
const initPieChart = () => {
  if (planData.value.length === 0) return;
  
  const canvas = document.getElementById('planPieChart');
  if (!canvas) return;
  
  const ctx = canvas.getContext('2d');
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 设置画布尺寸
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetWidth; // 正方形
  
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const radius = Math.min(centerX, centerY) * 0.8;
  
  let startAngle = 0;
  
  // 绘制饼图
  planData.value.forEach((item, index) => {
    if (item.count <= 0) return;
    
    const percentage = totalPlanCount.value > 0 ? item.count / totalPlanCount.value : 0;
    const endAngle = startAngle + percentage * 2 * Math.PI;
    
    // 绘制扇形
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.arc(centerX, centerY, radius, startAngle, endAngle);
    ctx.closePath();
    
    // 设置颜色
    const color = getPlanColor(index);
    ctx.fillStyle = color;
    ctx.fill();
    
    // 绘制边框
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    startAngle = endAngle;
  });
  
  // 绘制中心圆
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius * 0.4, 0, 2 * Math.PI);
  ctx.fillStyle = '#fff';
  ctx.fill();
  
  // 中心文本
  ctx.font = 'bold 16px sans-serif';
  ctx.fillStyle = '#333';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(`总计 ${totalPlanCount.value} 次`, centerX, centerY);
};

// 计算柱状图高度（最大高度为200px）
const getBarHeight = (count) => {
  if (maxCount.value === 0) return '0px';
  const height = (count / maxCount.value) * 200;
  return `${Math.max(height, 10)}px`; // 最小高度10px
};

// 计算试题库总题目数
const getTotalCount = (data) => {
  return data.reduce((sum, item) => sum + item.count, 0);
};

// 获取考试统计的颜色
const getPlanColor = (index) => {
  const colors = [
    '#1890ff', '#52c41a', '#faad14', '#f5222d',
    '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16'
  ];
  return colors[index % colors.length];
};

// 计算考试数量百分比
const getPercentage = (count) => {
  if (totalPlanCount.value === 0) return 0;
  return Math.round((count / totalPlanCount.value) * 100);
};

// 获取统计数据
const fetchStatistics = () => {
  loading.value = true;
  
  // 并行请求两个接口
  Promise.all([
    selectPaperStatic({}),
    selectPlanStatic({})
  ]).then(([paperRes, planRes]) => {
    // 处理试题库统计数据
    if (paperRes.code === 200 && paperRes.data) {
      paperData.value = paperRes.data;
      
      // 计算最大题目数量，用于柱状图比例
      let max = 0;
      paperRes.data.forEach(item => {
        item.data.forEach(d => {
          if (d.count > max) max = d.count;
        });
      });
      maxCount.value = max;
    } else {
      toast.msg('获取试题库统计失败');
    }
    
    // 处理考试统计数据
    if (planRes.code === 200 && planRes.data) {
      planData.value = planRes.data;
      
      // 计算考试总数量
      totalPlanCount.value = planRes.data.reduce((sum, item) => sum + item.count, 0);
    } else {
      toast.msg('获取考试统计失败');
    }
    
    loading.value = false;
  }).catch(err => {
    console.error('获取统计数据失败', err);
    toast.msg('获取统计数据失败，请重试');
    loading.value = false;
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchStatistics();
});

// 切换选项卡或数据更新时重新初始化饼图
onUpdated(() => {
  if (activeTab.value === 'plan' && planData.value.length > 0) {
    // 延迟初始化，确保DOM已更新
    setTimeout(initPieChart, 0);
  }
});
</script>

<style scoped lang="less">
.statistics-container {
  width: 100%;
  padding: 15px;
  box-sizing: border-box;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
  
  h1 {
    margin: 0;
    color: #333;
    font-size: 22px;
  }
  
  .desc {
    color: #666;
    margin: 8px 0 0;
    font-size: 13px;
  }
}

.tabs {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 15px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
  
  &.active {
    background-color: #1890ff;
    color: #fff;
    font-weight: 500;
  }
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 17px;
  color: #333;
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/* 题型图例 */
.type-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  padding-left: 5px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #666;
}

.type-marker {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 5px;
}

.type-1 {
  background-color: #1890ff;
}

.type-2 {
  background-color: #52c41a;
}

.type-3 {
  background-color: #faad14;
}

/* 柱状图样式 */
.bar-chart-container {
  display: flex;
  flex-direction: column;
  gap: 25px;
  padding: 10px 0 20px;
}

.chart-item {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  height: 220px;
  padding-bottom: 20px;
  position: relative;
}

.chart-label {
  width: 80px;
  font-size: 13px;
  color: #666;
  text-align: right;
  padding-right: 10px;
  flex-shrink: 0;
}

.chart-bars {
  flex-grow: 1;
  display: flex;
  gap: 10px;
  align-items: flex-end;
  height: 100%;
  padding-bottom: 20px;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 20px;
    left: 0;
    width: 100%;
    height: 1px;
    background-color: #eee;
  }
}

.chart-bar {
  flex: 1;
  border-radius: 4px 4px 0 0;
  min-width: 30px;
  transition: height 0.5s ease;
  position: relative;
  
  &::after {
    content: attr(title);
    position: absolute;
    bottom: -20px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 12px;
    color: #666;
    white-space: nowrap;
  }
}

.total-count {
  position: absolute;
  bottom: 0;
  left: 80px;
  font-size: 12px;
  color: #999;
}

/* 饼图容器 */
.pie-chart-container {
  padding: 10px 0;
}

/* 考试列表样式 */
.plan-list {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.plan-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.plan-color-marker {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: var(--color);
  margin-right: 10px;
}

.plan-name {
  flex-grow: 1;
  font-size: 14px;
  color: #333;
}

.plan-count {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.count-percentage {
  font-size: 12px;
  color: #999;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 60px 20px;
  
  .loading-spinner {
    color: #666;
    font-size: 14px;
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  
  .empty-icon {
    font-size: 40px;
    margin-bottom: 12px;
  }
  
  p {
    font-size: 14px;
  }
}

/* 响应式调整 */
@media (max-width: 375px) {
  .chart-label {
    width: 60px;
    font-size: 12px;
  }
  
  .total-count {
    left: 60px;
    font-size: 11px;
  }
}
</style>
